package 矩阵;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author tmh
 * @date 2024/11/27 20:37
 * @description
 */
public class T54螺旋矩阵 {
    public List<Integer> spiralOrder(int[][] matrix) {
        //定义四个变量分别保存四个边界点
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        if (matrix == null) {
            return new ArrayList<>();
        }
        Integer[] result = new Integer[(right + 1) * (bottom + 1)];
        //记录位置
        int index = 0;
        while (true) {
            //上面的行
            for (int i = left; i <= right; i++) {
                result[index++] = matrix[top][i];
            }
            top++;
            if (top > bottom) {
                break;
            }
            //右面的列,上下走
            for (int i = top; i <= bottom; i++) {
                result[index++] = matrix[i][right];
            }
            right--;
            if (right < left) {
                break;
            }
            //下面的行
            for (int i = right; i >= left; i--) {
                result[index++] = matrix[bottom][i];
            }
            bottom--;
            if (bottom < top) {
                break;
            }
            //左面的列
            for (int i = bottom; i >= top; i--) {
                result[index++] = matrix[i][left];
            }
            left++;
            if (left > right) {
                break;
            }
        }
        return Arrays.asList(result);
    }
}
